package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"lht-go-plugins/LhtLog"
	"os"
	"path/filepath"
)

var Conf = new(WebConfig)

type WebConfig struct {
	*WebServerConfig `mapstructure:"webConfig"`
}
type WebServerConfig struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
	//debug release
	Mode string `mapstructure:"mode"`
	// TLS TLS 配置项，若不启用 HTTPS 则为 nil
	TLS         *TLSConfig  `mapstructure:"tls"`
	CORS        *CORSConfig `mapstructure:"cors"`
	StaticDir   string      `mapstructure:"staticDir"`
	TemplateDir string      `mapstructure:"templateDir"`
	AllowedIPs  []string    `mapstructure:"allowedIPs"`
	//EnablePProf 是否开启 pprof 性能分析接口
	EnablePProf bool `mapstructure:"enablePProf"`
}
type TLSConfig struct {
	Enable   bool   `mapstructure:"enable"`
	CertFile string `mapstructure:"certFile"`
	KeyFile  string `mapstructure:"keyFile"`
}
type CORSConfig struct {
	AllowOrigins []string `mapstructure:"allowOrigins"`
	AllowMethods []string `mapstructure:"allowMethods"`
	AllowHeaders []string `mapstructure:"allowHeaders"`
}

func GetExeDir() string {
	exePath, _ := os.Executable()             // 获取当前执行文件的路径
	exeDir := filepath.Dir(exePath)           // 获取目录
	exeDir, _ = filepath.EvalSymlinks(exeDir) // 解决软链接问题
	return exeDir
}
func InitConfiguration() (err error) {
	viper.SetConfigFile(GetExeDir() + "/config/web.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		LhtLog.Error("Init config file failed, err:", zap.String("", err.Error()))
		return
	}

	//反序列化到结构体
	if err := viper.Unmarshal(Conf); err != nil {
		LhtLog.Error("\"viper unmarshal failed, err:", zap.String("", err.Error()))
	}

	// 监控并重新读取配置文件
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config file is changed...", in.Name)
		if err := viper.Unmarshal(Conf); err != nil {
			fmt.Printf("viper unmarshal failed, err: %v\n", err)
		}
	})
	return
}
